//
//  ProcessedOrder.m
//  RRBI
//
//  Created by kyjun on 16/4/26.
//
//

#import "ProcessedOrder.h"
#import "Login.h"
#import "Pager.h"
#import "MOrder.h"
#import "OrderCell.h"
#import "OrderHeader.h"
#import "FinishedOrderHeader.h"
#import "FinishedOrderFooter.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>


@interface ProcessedOrder ()<OrderHeaderDelegate,DZNEmptyDataSetSource,DZNEmptyDataSetDelegate>
@property(nonatomic,strong) Pager* page;
@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* finishedHeaderIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;
@end

@implementation ProcessedOrder

-(instancetype)init{
    self = [super initWithStyle:UITableViewStyleGrouped];
    if(self){
        [self.tabBarItem setImage:[UIImage imageNamed:@"tab-processed-order-default"]];
        [self.tabBarItem setSelectedImage:[[UIImage imageNamed:@"tab-processed-order-enter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
        [self.tabBarItem setTitle:@"已处理订单"];
        self.tabBarItem.tag=1;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"人人便利商家";
    self.cellIdentifier = @"OrderCell";
    self.finishedHeaderIdentifier = @"FinishedOrderHeader";
    self.headerIdentifier = @"OrderHeader";
    self.footerIdentitifer = @"FinishedOrderFooter";
    
    self.tableView.emptyDataSetSource = self;
    self.tableView.emptyDataSetDelegate = self;
    
    [self.tableView registerClass:[OrderCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[OrderHeader class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[FinishedOrderHeader class] forHeaderFooterViewReuseIdentifier:self.finishedHeaderIdentifier];
    [self.tableView registerClass:[FinishedOrderFooter class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(!self.Identity.userInfo.isLogin){
        UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:[[Login alloc]init]];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        [self refreshDataSource];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark =====================================================  Data source
-(void)queryData{
    AFHTTPRequestOperationManager* mgr = [AFHTTPRequestOperationManager manager];
    NSDictionary* arg = @{@"ince":@"get_order_list",@"sid":[UserModel sharedInstanced].ru_Id,@"page":[WMHelper integerConvertToString:self.page.pageIndex]};
    [mgr POST:kHost parameters:arg success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [WMHelper outPutJsonString:responseObject];
        if(self.page.pageIndex == 1){
            [self.page.arrayData removeAllObjects];
        }
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            self.page.recordCount = [[responseObject objectForKey:@"total"] integerValue];
            self.page.pageSize = [[responseObject objectForKey:@"number"]integerValue];
            NSInteger empty = self.page.recordCount % self.page.pageSize;
            if(empty == 0){
                self.page.pageCount = self.page.recordCount/self.page.pageSize;
            }else{
                self.page.pageCount = self.page.recordCount/self.page.pageSize+1;
            }
            
            NSArray* array = [responseObject objectForKey:@"data"];
            if(![WMHelper isNULLOrnil:array]){
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MOrder* item = [[MOrder alloc]initWithItem:obj];
                    [self.page.arrayData addObject:item];
                }];
            }
        }else{
            [self alertHUD:[responseObject objectForKey:@"msg"]];
        }
        [self.tableView reloadData];
        if(self.page.pageCount<=self.page.pageIndex){
            [self.tableView.mj_footer endRefreshingWithNoMoreData];
        }else{
            [self.tableView.mj_footer endRefreshing];
        }
        if(self.page.pageIndex==1){
            [self.tableView.mj_header endRefreshing];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.page.pageIndex = 1;
        [weakSelf queryData];
    }];
    
    self.tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        weakSelf.page.pageIndex ++;
        [weakSelf queryData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.page.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        return 1;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    MOrder* empty =self.page.arrayData[indexPath.section];
    cell.arrayGoods =empty.arrayGoods;
    return cell;
}

#pragma mark =====================================================  <UITableViewDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MOrder* empty =self.page.arrayData[indexPath.section];
    if(empty.isExpansion){
        return   empty.arrayGoods.count*45.f;
    }
    return 0;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
//        return 150.f;
        return 190.f;
    }else{
//        return   80.f;
        return   120.f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
//        return 140.f;
        return 180.f;
     }
    return 0.1;
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(!empty.isExpansion){
        FinishedOrderHeader* header =  (FinishedOrderHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.finishedHeaderIdentifier];
        [header loadData:self.page.arrayData[section] index:section+1];
        header.delegate = self;
        return header;
    }else{
        OrderHeader* header =  (OrderHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifier];
        [header loadData:self.page.arrayData[section] index:section+1];
        header.delegate = self;
        return header;
    }
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MOrder* empty =self.page.arrayData[section];
    if(empty.isExpansion){
        FinishedOrderFooter* footer = (FinishedOrderFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerIdentitifer];
        footer.entity = self.page.arrayData[section];
        return footer;
    }
    return [[UIView alloc]init];
}

- (BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

#pragma mark =====================================================  <OrderHeaderDelegate>
-(void)orderHeader:(MOrder *)entity{
    entity.isExpansion = !entity.isExpansion;
    [self.tableView reloadData];
}

#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无已处理订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}


#pragma mark =====================================================  property package
-(Pager *)page{
    if(!_page){
        _page = [[Pager alloc]init];
    }
    return _page;
}

@end
